const Router = require('koa-router');

const Message = require('../models/message')

let router = new Router({
  prefix: '/api'
})

router.post('/message/add', async (ctx) => {
  let {
    name,
    email,
    content
  } = ctx.request.body
  try {
    const newMessage = await Message.create({
      name,
      email,
      content,
      createTime: Math.round(new Date())
    })
    if (newMessage) {
      ctx.body = {
        code: 0,
        msg: '留言成功'
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '留言失败'
      }
    }
  } catch (err) {
    ctx.body = {
      code: -1,
      msg: '服务器异常'
    }
  }
})

router.get('/message/get', async (ctx) => {
  const {
    pageNo,
    limit
  } = ctx.request.query
  try {
    const result = await Message.find().limit(+limit).skip((pageNo - 1) * limit).sort({'createTime': -1})
    const count = await Message.count()
    if (result) {
      ctx.body = {
        code: 0,
        data: result,
        count: count
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '查询失败'
      }
    }
  } catch (err) {
    ctx.body = {
      code: -1,
      msg: '服务器异常'
    }
  }
})

module.exports = router